'''
Created on Dec 16, 2010

@author: mwicat
'''

import logging
logger = logging.getLogger(__name__)


import os, sys

from e32 import *
from appuifw import *
import appuifw2
import appuifw
import sysinfo

from uikludges import set_softkey_text, EAknSoftkeyExit, EAknSoftkeyOptions
from window import Application, Dialog, Splash

from sniffylib.core import application
from sniffylib.util import platform, uiutil

TITLE = u'Sniffy'

class ConsoleDialog(Dialog):
    def __init__(self, console, cbk):
        menu = [(u"Zamknij", self.close_app)]
        Dialog.__init__(self, cbk, u"Konsola", console, menu)


class SniffyUI(Application):
    
    def __init__(self, app, console, exit_handler=None):
        self.app = app
        self.console = console
        menu = [ 
                (u"Wl/wyl lello", app.lello_svc.toggle),
                (u"Wl/wyl zdalne ster.", app.rpc_svc.toggle),
                (u"Konsola", self.text_editor),
                (u"Wyjdz", self.close_app)]
        #self.body = appuifw.app.body
        self.body = appuifw2.Text_display(skinned=True)
        Application.__init__(self,  TITLE, self.body, menu, exit_handler=exit_handler)

    def close_app(self):
        Application.close_app(self)

    def text_editor(self):
        def cbk():
            self.refresh()
            return True
        self.dlg = ConsoleDialog(self.console, cbk)
        self.dlg.run()
        

    def run(self):
        self.splash_image = platform.get_resource_path('logo.png')
        logger.debug(self.splash_image)
        def cbk_splash():
            return True
        self.main_timer = Ao_timer()
        s = Splash(cbk_splash, self.splash_image, self.main_timer, 2)
        appuifw.app.screen = 'normal'
        Application.run(self)

def rename_exit_to_hide():
    set_softkey_text(EAknSoftkeyOptions, u'Opcje')
    set_softkey_text(EAknSoftkeyExit, u'Ukryj')

def background_exit_handler():
    platform.go_background()    

def bind_status_to_ui(ui, app):
    def update_cb(text):
        ui.body.set(unicode(text))
    updater = uiutil.TextStatusUpdater(update_cb=ao_callgate(update_cb))
    updater.register_service(u'lello', app.lello_svc)
    updater.register_service(u'zdalne sterowanie', app.rpc_svc)
    
def run(config):
    console = appuifw.app.body
    app = application.App(config)
    sniffy_ui = SniffyUI(app, console, exit_handler=background_exit_handler)
    app.launch()
    bind_status_to_ui(sniffy_ui, app)
    rename_exit_to_hide()
    sniffy_ui.run()
    sys.exit()

    